﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using JsonTest1.Data;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.Collections.Specialized;

namespace JsonTest1.Json
{
    public class TracksFunctions
    {
        public static Track[] getTracks(string json, bool sort)
        {

            JArray jsonArrayAlbums = JArray.Parse(json);
            if (jsonArrayAlbums == null)
            {
                throw new JsonException();
            }

            int n = jsonArrayAlbums.Count;
            Track[] albums = new Track[n];
            TrackBuilder albumBuilder = new TrackBuilder();
            for (int i = 0; i < n; i++)
            {
                albums[i] = albumBuilder.Build((JObject)jsonArrayAlbums[i]);
            }

            if (sort)
            {
                Array.Sort(albums,new TrackComparater());
            }
            return albums;
        }

        public static Playlist createPlaylist(Track[] aTracks, Album[] aAlbums, int[] aOrderBy) {
		if(aAlbums.Length != aTracks.Length)
			aAlbums = null;
		Playlist playlist = new Playlist();


        Dictionary<int, PlaylistEntry> bufferForOredr = new Dictionary<int, PlaylistEntry>();

		for(int i = 0; i < aTracks.Length; i++){
			PlaylistEntry playlistEntry = new PlaylistEntry();
			Album album=null;
			if(aAlbums != null){
				album = aAlbums[i];
                playlistEntry.Album = album;
			} else {
				/*album = getAlbumByTrackId(aTracks[i].Id);
				if(album == null){
					album = Album.emptyAlbum;
				}
                playlistEntry.Album = album;*/
			}
            playlistEntry.Track = aTracks[i];
            bufferForOredr.Add(aTracks[i].Id, playlistEntry);
			

			if(album != Album.emptyAlbum){
				//Log.i("jamendroid", aTracks[i].getName() +" by "+album.getArtistName());
			}else{
				//Log.i("jamendroid", aTracks[i].getName() +" without album");
			}
		}
		for(int i=0;i<aOrderBy.Length;i++){
			// Adding to playlist in correct order
            PlaylistEntry entry;
            bufferForOredr.TryGetValue(aOrderBy[i],out entry);
			playlist.addPlaylistEntry(entry);
		}
		return playlist;
	}

    }
}
